import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { UserModel } from '../interface'
import { listToggle } from '@/utils/listSlice'
import { flatAllTreeToList } from '../utils'
import { UserEntity } from '@/api/create/interface'

type StateStore = {
	tree: UserModel[]
	screenList: Omit<UserModel, 'children'>[]
	_start: string | null
	_changes: string[]
}

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	itemHandle: (actualUuid: string, type: 'click' | 'ctrl' | 'shift') => void
	toggleTree: (status: UserModel['status']) => void
	getUsers: (superMtNum: boolean) => UserEntity[]
}

const initialState: StateStore = {
	tree: [],
	screenList: [],
	_start: null,
	_changes: [],
}

export const useUserAllStore = create<IStore>()(
	subscribeWithSelector((set, get, api) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		itemHandle: (actualUuid, type) => {
			const { screenList, _start, _changes } = get()
			const result = listToggle(
				screenList,
				{
					_start,
					_changes,
					action: type,
					path: 'attr.actualUuid',
				},
				actualUuid
			)
			set({ screenList: result.list, _start: result._start, _changes: result._changes })
		},
		toggleTree: (status) => {
			status.isOpen = !status.isOpen
			set((v) => ({ tree: [...v.tree] }))
		},
		getUsers: (superMtNum) => {
			const tree = get().tree
			return tree.map((x) => ({
				account: x.mcc.account,
				account_type: x.mcc.account_type,
				name: x.mcc.name,
				bitrate: x.mcc.bitrate,
				protocol: x.mcc.protocol,
				interactive_mt: superMtNum ? (x.status.isInteractive ? 1 : 0) : 1, //非超大方互动标识符统一下参为 1
			}))
		},
	}))
)

useUserAllStore.subscribe(
	(state) => state.tree,
	(tree) => {
		const l = flatAllTreeToList(tree)
		useUserAllStore.setState({ screenList: l })
	}
)
